package com.program.beautymakeup.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.crypto.digest.MD5;
import com.program.beautymakeup.controller.form.UserForm;
import com.program.beautymakeup.domain.bo.UserQueryBO;
import com.program.beautymakeup.domain.entity.User;
import com.program.beautymakeup.controller.form.LoginForm;
import com.program.beautymakeup.domain.vo.PageVO;
import com.program.beautymakeup.domain.vo.ResultInfo;
import com.program.beautymakeup.domain.vo.UserVO;
import com.program.beautymakeup.service.UploadService;
import com.program.beautymakeup.service.UserService;
import com.program.beautymakeup.utils.JwtUtil;
import com.program.beautymakeup.utils.ResultInfoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author CaiKe
 * @date 2023/2/8 20:42
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final JwtUtil jwtUtil;
    private final UserService userService;
    private final UploadService uploadService;

    @PostMapping("/login")
    public ResultInfo<String> login(@RequestBody @Valid LoginForm loginForm) {
        log.info("username【{}】, password【{}】", loginForm.getUsername(), loginForm.getPassword());
        User user = userService.login(loginForm.getUsername(), loginForm.getPassword());
        if (user != null) {
            StpUtil.login(user.getUserId());
            return ResultInfoUtil.buildSuccess();
        } else {
            return ResultInfoUtil.buildError(401, "账号或密码错误！");
        }
    }

    @PostMapping("/sub/list")
    @SaCheckLogin
    public ResultInfo<PageVO<UserVO>> queryList(@Valid @RequestBody UserQueryBO userQueryBO) {
        return ResultInfoUtil.buildSuccess(userService.queryList(userQueryBO));
    }


    /**
     * 添加员工（需要一级管理权限）
     */
    @PostMapping("/sub")
    @SaCheckRole(value = "1")
    public ResultInfo<Void> addSecondUser(@Valid UserForm userForm, MultipartFile avatar) {
        //log.info("request.getContentType:{}",request.getContentType());
        if (userService.countUserByUsername(userForm.getUsername()) > 0) {
            return ResultInfoUtil.buildError("用户名已存在");
        }
        final MD5 md5 = new MD5();
        userForm.setPassword(md5.digestHex(userForm.getPassword()));
        final User userToSave = new User();
        BeanUtils.copyProperties(userForm, userToSave);
        if(avatar != null){
            final String avatarUrl = uploadService.uploadImg(ListUtil.of(avatar));
            userToSave.setAvatar(avatarUrl);
        }
        userService.saveUser(userToSave);
        return ResultInfoUtil.buildSuccess();
    }

    @DeleteMapping("/sub/{id}")
    @SaCheckRole(value = "1")
    public ResultInfo<Void> deleteSecondUser(@PathVariable("id") Integer id) {
        userService.deleteUserById(id);
        return ResultInfoUtil.buildSuccess();
    }

    @GetMapping("/sub/{id}")
    @SaCheckLogin
    public ResultInfo<User> findUserById(@PathVariable("id") Integer id) {
        return ResultInfoUtil.buildSuccess(userService.getUserInfo(id));
    }

    @PutMapping("/sub")
    @SaCheckLogin
    public ResultInfo<Void> updateUserInfo(@Valid UserForm userForm, MultipartFile avatar, HttpServletRequest request) {
        final User userToSave = new User();
        BeanUtils.copyProperties(userForm, userToSave);
        if(avatar != null){
            final String avatarUrl = uploadService.uploadImg(ListUtil.of(avatar));
            userToSave.setAvatar(avatarUrl);
        }
        userToSave.setUserId((int) StpUtil.getLoginIdAsLong());
        userService.updateUser(userToSave);
        return ResultInfoUtil.buildSuccess();
    }
    @PutMapping("/sub/{userId}")
    @SaCheckLogin
    @SaCheckRole("1")
    public ResultInfo<Void> updateUserInfo(@PathVariable Integer userId,@Valid UserForm userForm, MultipartFile avatar, HttpServletRequest request) {
        final User userToSave = new User();
        BeanUtils.copyProperties(userForm, userToSave);
        if(avatar != null){
            final String avatarUrl = uploadService.uploadImg(ListUtil.of(avatar));
            userToSave.setAvatar(avatarUrl);
        }
        userToSave.setUserId(userId);
        userService.updateUser(userToSave);
        return ResultInfoUtil.buildSuccess();
    }

    @PutMapping("/sub/list")
    @SaCheckLogin
    public ResultInfo<Void> sublist(@Valid UserForm userForm, MultipartFile avatar, HttpServletRequest request) {
        return null;
    }


}